<template>
  <div class="market-rule">
    <div
      class="top-container"
      style="margin-bottom:20px;"
    >
      <el-row>
        <el-col :span="4">
          <el-button
            v-auth="{v: ['crm:marketing:rule:add'], bool: disObj.show}"
            class="border-btn"
            size="mini"
            @click="addMarketRule"
          >添加市场规则</el-button>
        </el-col>
        <el-col :span="20">
          <div style="display: flex; justify-content: flex-end">
            <el-form
              :model="formData"
              label-position="right"
              size="small"
              class="filter-form-inline"
            >
              <el-form-item
                label="选择地区"
                style="width:300px;margin-bottom:0px;"
              >
                <el-cascader
                  ref="cascader"
                  v-model="filterData.codeList"
                  :popper-append-to-body="false"
                  style="width: 100%;"
                  :options="citys.map(v => ({...v, children: v.children.map(o => ({...o, children: null}))}))"
                  placeholder="请选择地区"
                  :props="{ checkStrictly: true, expandTrigger: 'hover', label: 'regionName', value:'regionCode' }"
                  collapse-tags
                  clearable
                  @change="areaChange"
                />
              </el-form-item>
            </el-form>
          </div>
        </el-col>
      </el-row>
    </div>
    <div class="my-table-list">
      <table
        style="width:100%"
        border="1"
        cellspacing="0"
      >
        <thead>
          <tr>
            <th align="center">省份</th>
            <th align="center">地 / 市</th>
            <th align="center">区 / 县</th>
            <!--<th align="center">市场进化属性</th>-->
            <th align="center">市场营销模式</th>
            <th
              v-if="disObj.show"
              align="center"
            >操作</th>
          </tr>
        </thead>
        <tbody v-if="listData.length">
          <tr
            v-for="(item, index) in listData"
            :key="index"
          >
            <td
              align="center"
              style="min-width: 160px"
            >
              <span>{{ item.provinceName }}</span>
            </td>
            <td
              align="center"
              style="padding:0px;min-width: 160px"
            >
              <div
                v-for="(itm,idx) in item.cityList"
                :key="idx"
                style="padding: 0px 5px;"
                :style="{'border-bottom': idx<item.cityList.length-1?'1px solid #dcdfe6':''}"
              >
                <span>{{ itm.cityName }}</span>
              </div>
            </td>
            <td
              align="center"
              style="padding:0px"
            >
              <div
                v-for="(itm,idx) in item.cityList"
                :key="idx"
                style="padding: 0px 5px;"
                :style="{'border-bottom': idx<item.cityList.length-1?'1px solid #dcdfe6':''}"
              >
                <area-list :area="itm.areas" />
              </div>
            </td>
            <!--
            <td
              align="center"
              style="padding:0px;min-width: 120px"
            >
              <div
                v-for="(itm,idx) in item.cityList"
                :key="idx"
                style="padding: 0px 5px;"
                :style="{'border-bottom': idx<item.cityList.length-1?'1px solid #dcdfe6':''}"
              >
                <span>{{ getLabel('product_attribute', itm.maturity) }}</span>
              </div>
            </td>
            -->
            <td
              align="center"
              style="padding:0px;min-width: 120px"
            >
              <div
                v-for="(itm,idx) in item.cityList"
                :key="idx"
                style="padding: 0px 5px;"
                :style="{'border-bottom': idx<item.cityList.length-1?'1px solid #dcdfe6':''}"
              >
                <span
                  v-for="(con, ci) in itm.marketSellMode"
                  :key="ci"
                >{{ getLabel('market_sell_mode', con) }}<i v-if="ci<itm.marketSellMode.length-1">，</i></span>
              </div>
            </td>
            <td
              v-if="disObj.show"
              align="center"
              style="padding:0px;min-width: 120px"
            >
              <div
                v-for="(itm,idx) in item.cityList"
                :key="idx"
                style="padding: 0px 5px;"
                :style="{'border-bottom': idx<item.cityList.length-1?'1px solid #dcdfe6':''}"
              >
                <el-button
                  v-auth="{v: ['crm:marketing:rule:edit']}"
                  type="text"
                  @click="editMarketRule(item,itm)"
                >编辑</el-button>
                <el-button
                  v-auth="{v: ['crm:marketing:rule:delete']}"
                  type="text"
                  class="danger"
                  @click="deleteItem(itm)"
                >删除</el-button>
              </div>
            </td>
          </tr>
        </tbody>
        <tbody v-else>
          <tr>
            <td
              :colspan="6"
              align="center"
              style="color: #999;"
            >暂无数据</td>
          </tr>
        </tbody>
      </table>
    </div>
    <!-- 添加市场规则 -->
    <create-rule-dialog
      ref="createRuleRef"
      @refresh="refreshList"
    />
  </div>
</template>
<script>
import areaList from './areaList.vue'
import {
  defineAsyncComponent,
  defineComponent,
  getCurrentInstance,
  inject,
  onMounted,
  reactive,
  ref,
  toRefs,
  watch,
} from 'vue'
import { useRoute } from 'vue-router'
import { crmStore } from '@CRM/store'
import area from '@/utils/area.js'

export default defineComponent({
  components: {
    areaList,
    createRuleDialog: defineAsyncComponent(() =>
      import('./createRuleDialog.vue')
    ),
  },
  props: {
    detail: {
      type: Object,
      default: () => {},
    },
  },
  setup(props, context) {
    const route = useRoute()
    const currentInstance = getCurrentInstance()
    const api = inject('api')
    var createRuleRef = ref(null)
    var types = ref('create')
    var productDetail = reactive(props.detail)
    var datas = reactive({
      citys: area,
      disObj: { show: true, msg: '' },
      listData: [],
      filterData: {
        productId: Number(route.query.productId) || 0,
        codeList: [],
        provinceCode: '',
        cityCode: '',
      },
      marketMaturity:
        crmStore.getters['dictionary/getDictionary']['product_attribute'],
      marketSellModeOption:
        crmStore.getters['dictionary/getDictionary']['market_sell_mode'],
    })
    // 获取列表
    const getList = () => {
      api.marketRule.MARKET_RULE_LIST(datas.filterData).then((res) => {
        if (res.code === 0) {
          console.log(res.data.list)
          var obj = res.data.list
          var list = []
          for (var key in obj) {
            var item = {
              provinceCode: obj[key][0].provinceCode,
              provinceName: obj[key][0].provinceName,
              cityList: obj[key],
            }
            list.push(item)
          }
          datas.listData = list
          console.log(datas.listData)
        }
      })
    }
    // 更新列表
    const refreshList = () => {
      getList()
    }
    // 添加市场规则
    const addMarketRule = () => {
      createRuleRef.value.open({ types: 'create', data: null })
    }
    // 编辑市场规则
    const editMarketRule = (item, itm) => {
      console.log(item, itm)
      createRuleRef.value.open({ types: 'edit', data: itm })
    }
    // 删除规则
    const deleteMarketRule = (itm) => {
      console.log(itm)
      api.marketRule.MARKET_RULE_DELETE({ id: itm.id }).then((res) => {
        if (res.code === 0) {
          currentInstance.proxy.customMessage({
            type: 'success',
            message: '删除成功',
          })
          refreshList()
        }
      })
    }

    // 删除产品
    const deleteItem = (itm) => {
      console.log(currentInstance.proxy)
      currentInstance.proxy
        .alertBox({
          message: '数据删除后不可恢复，确定删除？',
          title: '市场规则删除',
        })
        .then(() => {
          deleteMarketRule(itm)
        })
        .catch((err) => {
          console.log(err)
        })
    }
    const areaChange = (val) => {
      if (val && val.length) {
        datas.filterData.provinceCode = val[0]
        datas.filterData.cityCode = val[1] || ''
      } else {
        datas.filterData.provinceCode = ''
        datas.filterData.cityCode = ''
      }
      refreshList()
    }
    // 判断操作按钮是否可用
    const isCreatePrice = () => {
      if (productDetail.productStatus === '-1') {
        datas.disObj.show = false
        datas.disObj.msg = '产品审核未通过，暂不支持创建产品价格'
      }
      if (productDetail.productStatus === '-4') {
        datas.disObj.show = false
        datas.disObj.msg = '产品已下架'
      }
      if (productDetail.productStatus === '1') {
        datas.disObj.show = false
        datas.disObj.msg = '产品审核中'
      }
    }
    onMounted(() => {
      getList()
    })
    watch(
      () => props.detail,
      (newval, oldval) => {
        if (newval) {
          productDetail = newval
          isCreatePrice()
        }
      },
      {
        immediate: true,
      }
    )
    return {
      types,
      createRuleRef,
      ...toRefs(datas),
      deleteItem,
      addMarketRule,
      editMarketRule,
      refreshList,
      areaChange,
    }
  },
})
</script>
<style lang="scss" scoped>
.my-table-list {
  table {
    color: #303133;
    border-right: 1px solid #dcdfe6;
    border-bottom: 1px solid #dcdfe6;
    border-collapse: collapse;
    thead {
      background: #f8f8f8;
      tr {
        border: 1px solid #dcdfe6;
        th {
          line-height: 40px;
          font-size: 14px;
          padding: 5px;
          color: #909399;
          border-left: 1px solid #dcdfe6;
          border-top: 1px solid #dcdfe6;
        }
      }
    }
    tr {
      border: 1px solid #dcdfe6;
      td {
        line-height: 40px;
        font-size: 14px;
        padding: 5px;
        color: #303133;
        border-left: 1px solid #dcdfe6;
        border-top: 1px solid #dcdfe6;
      }
    }
  }
}
</style>
